const http = require('../../utils/http.js');
const tools = require('../../utils/tools.js')
// 注册页面

Page({
  data: {
    base_candidate_info: {
      id: '',
      id_number: '',
      name: '',
      gender: '',
      birth_date: '',
      ethnicity_id: '',
      political_status_id: '',
      foreign_language_id: '',
      phone: '',
      password: ''
    },
    genderOptions: ['男', '女'],
    genderIndex: null,
    ethnicityOptions: [],
    ethnicityIndex: null,
    politicalStatusOptions: [],
    politicalStatusIndex: null,
    foreignLanguageOptions: [],
    foreignLanguageIndex: null,
    recognitionResult: '',

    recordedText:null,
    recording: false,  // 用于标记当前是否正在录音
    isPaused: false,   // 用于标记录音是否处于暂停状态
    recordFilePath: '',  // 用于保存录音文件的临时路径
    editableContent: '', // 用于保存识别后文本内容的初始化
    buttonText: '开始录音', // 新增按钮文本控制变量
  },

  onLoad() {
    // 获取所有选项数据
    const ethnicityPromise = tools.fetchOptions('/ethnicity/list', 'ethnicityOptions', this);
    const politicalStatusPromise = tools.fetchOptions('/politicalstatus/list', 'politicalStatusOptions',this);
    const foreignLanguagePromise = tools.fetchOptions('/foreignlanguage/list', 'foreignLanguageOptions',this);
  
    // 等待所有请求完成
    Promise.all([ethnicityPromise, politicalStatusPromise, foreignLanguagePromise]).then(() => {
      // 确保所有数据加载完成
    }).catch(err => {
      console.error('加载选项数据失败:', err);
    });
  },
  
  updateIndex(storedInfo){
    this.setData({
      genderIndex: this.data.genderOptions.indexOf(storedInfo.gender),
      ethnicityIndex: tools.findIndexById(this.data.ethnicityOptions, storedInfo.ethnicity_id),
      politicalStatusIndex: tools.findIndexById(this.data.politicalStatusOptions, storedInfo.political_status_id),
      foreignLanguageIndex: tools.findIndexById(this.data.foreignLanguageOptions, storedInfo.foreign_language_id),
    })
},  

  handleDateChange(e) {
    this.setData({
      'base_candidate_info.birth_date' : e.detail.value // 直接绑定选中的日期
    });
  },
  handlePickerChange(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({
      // 给对应的下标进行赋值
      [`${field}Index`]: e.detail.value,
      // 根据获取的下标在对应的 Options 里获取对应的 value，并赋值给 base_candidate_info 中的对应变量
      [`base_candidate_info.${field}`]: this.data[`${field}Options`][e.detail.value]
    });
  },
  handleEthnicityChange(e){
    const { field } = e.currentTarget.dataset;
    const index = e.detail.value;
    const id = this.data.ethnicityOptions[index].id
    // console.log(index)
    // console.log(this.data.ethnicityOptions[index])
    // console.log(id)
    this.setData({
      // 给对应的下标进行赋值
      [`${field}Index`]: index,
      // 根据获取的下标在对应的 Options 里获取对应的 value，并赋值给 base_candidate_info 中的对应变量
      'base_candidate_info.ethnicity_id':id
    });
  },
  handlePoliticalChange(e){
    const { field } = e.currentTarget.dataset;
    const index = e.detail.value;
    const id = this.data.ethnicityOptions[index].id
    this.setData({
      // 给对应的下标进行赋值
      [`${field}Index`]: index,
      // 根据获取的下标在对应的 Options 里获取对应的 value，并赋值给 base_candidate_info 中的对应变量
      'base_candidate_info.political_status_id':id
    });
  },
  handleForeignLanguageChange(e){
    const { field } = e.currentTarget.dataset;
    const index = e.detail.value;
    const id = this.data.ethnicityOptions[index].id
    this.setData({
      // 给对应的下标进行赋值
      [`${field}Index`]: index,
      // 根据获取的下标在对应的 Options 里获取对应的 value，并赋值给 base_candidate_info 中的对应变量
      'base_candidate_info.foreign_language_id':id
    });
  },
  handleInput(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({
      [`base_candidate_info.${field}`] : e.detail.value,
    });
  },

  handleSubmit(){
    // 注册验证
    const errors = tools.validateCandidateInfo(this.data.base_candidate_info,true);
    if (errors.length > 0) {
      wx.showToast({
        title: errors[0],
        icon: "none",
        duration: 2000,
      });
      return;
    }

    const base_candidate_info = {
      id_number: this.data.base_candidate_info.id_number,
      name: this.data.base_candidate_info.name,
      gender: this.data.base_candidate_info.gender, 
      birth_date: this.data.base_candidate_info.birth_date,
      ethnicity_id: this.data.base_candidate_info.ethnicity_id, 
      political_status_id: this.data.base_candidate_info.political_status_id, 
      foreign_language_id: this.data.base_candidate_info.foreign_language_id, 
      phone: this.data.base_candidate_info.phone,
      password: this.data.base_candidate_info.password
    };
    console.log(base_candidate_info)
    http.post("/candidate/register",base_candidate_info).then(res=>{
      console.log(res);
      if(res.data.code == 200){
        // wx.setStorageSync('base_candidate_info', base_candidate_info)
        wx.showToast({
          title: '注册成功',
          duration:3000
        })
        // 跳转页面
        wx.reLaunch({
          url:`/pages/login/login?id_number=${this.data.base_candidate_info.id_number}&password=${this.data.base_candidate_info.password}`,
        })
      }
    }).catch(err=>{
      console.log(err);
      wx.showToast({
        title: '注册失败',
        duration:2000
      })
    })
  },
  
  // 录音功能区
  toggleRecording() {
    if (this.data.recording) {
      // 停止录音逻辑
      this.setData({ recording: false });
      const recorderManager = wx.getRecorderManager();
      recorderManager.stop();
      recorderManager.onStop((res) => {
      // 将录音文件临时路径存储到本地存储
      wx.setStorageSync('recordPath', res.tempFilePath);
      this.setData({ recordFilePath: res.tempFilePath });
      this.setData({ buttonText: '开始录音' });
      });
    } else {
      // 检查录音权限
      tools.checkRecordPermission().then(() => {
      // 开始录音逻辑
      this.setData({ recording: true , buttonText: '停止录音'});
      const recorderManager = wx.getRecorderManager();
      recorderManager.start({
        format: 'wav', // 设置为wav格式
        duration: 60000, 
        sampleRate: 44100, 
        numberOfChannels: 1, 
        encodeBitRate: 96000
      });
      // that.setData({ buttonText: '停止录音' });
      }).catch((error) => {
          wx.showToast({
              title: error,
              icon:'none'
          });
      });
    }
  },
  
  // 上传录音并进行语音识别函数
  uploadAndRecognizeRecording() {
    if (!this.data.recordFilePath) {
        wx.showToast({ title: '请先录制录音', icon: 'none' });
        return;
    }
    const filePath = this.data.recordFilePath;
    // 调用后端识别接口
    http.asr(filePath).then(res =>{
      console.log("语音识别成功，文本如下：")
      console.log(res);
      // 根据返回的文本信息，提取其中的信息
      this.setData({ editableContent: res});
      // 调用后端的提取接口
      const postData = { "text": res };
      http.zsbExtract(postData).then(res =>{
        // 处理提取后的结果
        console.log("this is regist page ,the extract res:",res)
        console.log("this is ")
        // this.updateIdAndIndex(res.data.data)
        this.updateIdAndIndex(res.data)
      }).catch(err => {
        // 提取失败
        console.log('无法解析识别结果：', err);
        console.log('接收到的原始返回数据：', err.data);
      });
    }).catch(err =>{
      // 语音识别失败
      console.log('语音识别失败：', err);
      wx.showToast({ title: '录音识别失败', icon: 'none', duration: 2000 });
    })
  },
  updateIdAndIndex(dataFields){
    const fields = ["id_number", "name", "gender", "birth_date", "phone", "password"]
    const idFields={
        ethnicity: 'ethnicity_id',
        political_status: 'political_status_id',
        foreign_language: 'foreign_language_id'
    }
    const arrayFields = {
        ethnicity: 'ethnicityOptions',
        political_status: 'politicalStatusOptions',
        foreign_language: 'foreignLanguageOptions'
    }
    // 根据结果给字段赋值
    fields.forEach(key =>{
        if(!dataFields[key].includes("未知")){
            this.setData({
                [`base_candidate_info.${key}`]:dataFields[key]
            })
        }
    })
    // 根据名字赋值id
    Object.entries(idFields).forEach(([key,value]) =>{
        // 通过两个字典的映射获取对应的值，查询id随后进行赋值
        if(!dataFields[key].includes("未知")){
            this.setData({
                [`base_candidate_info.${value}`]:tools.findIdByName(this.data[arrayFields[key]],dataFields[key])
            })
        }
    })
    //更新下标
    this.updateIndex(this.data.base_candidate_info)
},
});